package com.tfjybj.itoo.teach.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.dmsdbj.itoo.tool.constantutil.YearSemester;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.teach.entity.StudentTeachClassEntity;
import com.tfjybj.itoo.teach.entity.TeachClassEntity;
import com.tfjybj.itoo.teach.entity.TeacherTeachClassEntity;
import com.tfjybj.itoo.teach.model.*;
import com.tfjybj.itoo.teach.provider.dao.TeachClassDao;
import com.tfjybj.itoo.teach.provider.service.*;
import com.tfjybj.itoo.teach.template.TeachClassExportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jplus.hyberbin.excel.utils.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.tfjybj.itoo.teach.provider.until.DemoConstants.*;

/**
 * TeachClassService接口实现类
 * ${base}表
 *
 * @author 田成荣
 * @version 2.0.0
 * @since 2.0.0 2018-11-08 19:34:10
 */
@Service("teachClassService")
@Slf4j
public class TeachClassServiceImpl extends BaseServicePlusImpl<TeachClassDao, TeachClassEntity> implements TeachClassService {

    @Resource
    private TeachClassDao teachClassDao;

    @Resource
    private TeacherTeachClassService teacherTeachClassService;

    @Resource
    private StudentTeachClassService studentTeachClassService;


    @Resource
    private AdmTeachClassService admTeachClassService;

    @Resource
    private TrainingTeachClassService trainingTeachClassService;


    @Resource
    private TeachClassService teachClassService;

    @Resource
    private RedisTemplate redisTemplate;


    @Resource
    private CourseService courseService;

    @Override
    public PageInfo<TeachClassModel> queryByLikeName(String name, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(teachClassDao.queryLikeName(name));
    }
    //endregion

    /* **********************************以下为非模板生成的内容********************************* */


    @Override
    public int queryRemCapacityByTeachClassId(String teachClassId) {
        return teachClassDao.queryRemCapacityByTeachClassId(teachClassId);
    }


    @Override
    public PageInfo<TeachClassModel>  queryTeachClassInfoByCodeAndNameStrLike(String teachClassCode, String teachClassName, String schoolYear, Integer pageNo, Integer pageSize){
        teachClassCode = teachClassCode.trim();
        teachClassName = teachClassName.trim();
        schoolYear = schoolYear.trim();
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<>(teachClassDao.queryTeachClassInfoByCodeAndNameStrLikeorsr(teachClassCode, teachClassName,schoolYear));
    }
    @Override
    public List<TeachClassModel>  queryTeachClassInfoByCodeAndNameStrLike(String teachClassCode, String teachClassName){
        teachClassCode = teachClassCode.trim();
        teachClassName = teachClassName.trim();
        return  teachClassDao.queryTeachClassInfoByCodeAndNameStrLike(teachClassCode, teachClassName);
    }
    @Override
    public ItooResult teachClassExport(HttpServletResponse response, String teachClassCode, String teachClassName){
        Map<Serializable,Serializable> map=new HashMap<>(16);
        map.put(SHEET_NAME,"上课班信息");
        //要导出的字段
        map.put(COLUMNS,new String[]{"code","name","courseCode","courseName","schoolYear", "capacity", "updateTime"});
        //导出表格的标题
        map.put(TITLE,"上课班信息");
        map.put(NAME,"上课班信息表");
        //要导出的数据
        List<TeachClassExportTemplate> teachClassExportTemplates=new ArrayList<>();
        List<TeachClassModel> teachClassModels=teachClassService.queryTeachClassInfoByCodeAndNameStrLike(teachClassCode,teachClassName) ;

        for (TeachClassModel teachClassModel:teachClassModels){
            TeachClassExportTemplate teachClassExportTemplate=new TeachClassExportTemplate();
            BeanUtils.copyProperties(teachClassModel,teachClassExportTemplate);
            teachClassExportTemplates.add(teachClassExportTemplate);
        }
        //为空不进行导出
        if (teachClassExportTemplates.size()==0){
            return ItooResult.build(ItooResult.FAIL, "没有要导出的数据！");
        }
        map.put(DATA_LIST,(Serializable) teachClassExportTemplates);
        //导出
        try {
            ExcelUtil.exportExcel(map,response);
        } catch (Exception e) {
            log.error("导出失败,未知的异常--"+e);
            return ItooResult.build(ItooResult.FAIL, "导出信息失败！");
        }
        return ItooResult.build(ItooResult.SUCCESS  , "导出信息成功！");
    }


    @Override
    public int updateRemCapacityByTeachClassId(String teachClassId, int remCapacity) {
        return teachClassDao.updateRemCapacityByTeachClassId(teachClassId, remCapacity);
    }

    @Override
    public PageInfo<StudentModel> queryStudentInfoByTeachClassId(String teachClassId, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(teachClassDao.queryClassInfoByTeacherClassId( teachClassId));
    }

    @Override
    public  Integer queryIsExitTeachClassCode(String teachClassCode){
        return teachClassDao.queryIsExitTeachClassCode(teachClassCode);
    }

    @Override
    public String queryIsExitTeachClassName(String teachClassName) {
        return teachClassDao.queryIsExitTeachClassName(teachClassName);
    }


    @Override
    public String findTeachClassName(String grade, String courseName) {
        //策略使用生成上课班名称
        String teachClassName;
        if (StringUtils.isEmpty(grade)) {
            teachClassName = courseName;
        } else {
            teachClassName = grade + courseName;
        }
        int teachClassNameCount = (int) teachClassDao.selectCount(teachClassName);
        int count = teachClassNameCount + 1;
        return teachClassName + count + "班";
    }

    @Override
    public boolean downLoadTeachClassTemplate(HttpServletResponse response){
        Map<Serializable, Serializable> map = new HashMap<>(16);
        List<TeachClassExportTemplate> templateList = new ArrayList<>();
        TeachClassExportTemplate teachClassExportTemplate = new TeachClassExportTemplate();

        //添加下载模板范例
        teachClassExportTemplate.setCode("388539");
        teachClassExportTemplate.setName("中国近代历史人物评说1班");
        teachClassExportTemplate.setSchoolYear("2017-2018学年第二学期");
        teachClassExportTemplate.setCourseCode("00000005");
        teachClassExportTemplate.setCourseName("教师职业能力训练（1）");
        teachClassExportTemplate.setCapacity("99");
        templateList.add(teachClassExportTemplate);

        //sheet的名字
        map.put(SHEET_NAME, "上课班信息");
        //需要导入的字段
        map.put(COLUMNS, new String[]{"code","name","courseCode","courseName","schoolYear",
                "capacity"});
        //表格的标题
        map.put(TITLE, "上课班信息");
        map.put(NAME, "上课班信息模板");
        map.put(DATA_LIST, (Serializable) templateList);
        try {
            ExcelUtil.exportExcel(map, response);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public ItooResult importTeachClassByTemplate(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response){
        response.setContentType("UTF-8");
        try {
            //校验文件是否存在
            String fileName = multipartFile.getOriginalFilename();
            if (fileName == null) {
                log.error("导入失败,fileName is null!");
                return ItooResult.build(ItooResult.FAIL, "传入的文件为空！");
            }
            //EXCEL解析成List
            Map<Serializable, Serializable> map = new HashMap<>(4);
            map.put(SHEET_NAME, "上课班信息");
            map.put(CLASS, TeachClassExportTemplate.class);
            List<TeachClassExportTemplate> teachClassExportTemplateList = ExcelUtil.importExcel(Objects.requireNonNull(fileName), map, request, response);

            if (teachClassExportTemplateList.size() == 0) {
                return ItooResult.build(ItooResult.FAIL, "导入的数据为空，请填写！");
            }
            //定义导入的错误数据集合并存redis中形式的<String,TeachClassExportTemplate>
            List<TeachClassExportTemplate> errorTPTList = new ArrayList<>();
            String errorTPTListId = IdWorker.getIdStr();
            Long size = redisTemplate.opsForZSet().size(errorTPTListId);
            size = size == null ? 0L : size;

            for (TeachClassExportTemplate excelTPT : teachClassExportTemplateList) {

                if (!this.verify(excelTPT)) {
                    TeachClassExportTemplate teachClassExportTemplate = new TeachClassExportTemplate();
                    BeanUtils.copyProperties(excelTPT, teachClassExportTemplate);

                    errorTPTList.add(teachClassExportTemplate);
                    redisTemplate.opsForZSet().add(errorTPTListId, teachClassExportTemplate, size + 1);
                    continue;
                }
                    TeachClassEntity teachClassEntity=insertValue(excelTPT);
                this.save(teachClassEntity);

            }
            //不符合条件的信息返回
            if (errorTPTList.size() > 0) {
                return ItooResult.build("0001","部分导入失败",errorTPTListId);
            }
        }
        catch(Exception e)
        {
            return ItooResult.build(ItooResult.FAIL, "导入数据异常！",e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导入数据成功！");
    }

    /**
     * 将模板的值插入实体中-导入专用
     *
     * @param teachClassExportTemplate 模板
     * @return 严文文
     * @since 2.0.0 2018-12-2 16:49:41
     */
    private TeachClassEntity insertValue(TeachClassExportTemplate teachClassExportTemplate){
        TeachClassEntity teachClassEntity = new TeachClassEntity();
        //将导入内容放到entity中对应的属性中去
        BeanUtils.copyProperties(teachClassExportTemplate, teachClassEntity);
        List<CourseModel> courseModels=courseService.findByCode(teachClassExportTemplate.getCourseCode()) ;
        String courseId=courseModels.get(0).getId();
        //课程id
        teachClassEntity.setCourseId(courseId);
        //上课班ID
        teachClassEntity.setId(IdWorker.getIdStr());
        //可用
        teachClassEntity.setIsDelete(0);
        //上课班名称
        teachClassEntity.setName(teachClassExportTemplate.getName());
        teachClassEntity.setSchoolYear(teachClassExportTemplate.getSchoolYear());
        teachClassEntity.setCapacity(Integer.parseInt(teachClassExportTemplate.getCapacity()));

        //上课班代码
        teachClassEntity.setCode(teachClassExportTemplate.getCode());

        //选填数据
        //操作者
        teachClassEntity.setOperator("大米时代");
        return   teachClassEntity;

    }

            private boolean verify(TeachClassExportTemplate excelTPT )
            {
                if (StringUtils.isEmpty(excelTPT.getCode())) {
                    excelTPT.setFailReason("上课班代码未填写");
                    log.warn("导入失败,上课班代码未填写,excelFooEntity-{}", excelTPT);
                    return false;
                }
                if (StringUtils.isEmpty(excelTPT.getName())) {
                    excelTPT.setFailReason("上课班名称未填写");
                    log.warn("导入失败,上课班名称未填写,excelFooEntity-{}", excelTPT);
                    return false;
                }
                if (StringUtils.isEmpty(excelTPT.getCourseCode())) {
                    excelTPT.setFailReason("课程代码未填写");
                    log.warn("导入失败,课程代码未填写,excelFooEntity-{}", excelTPT);
                    return false;
                }
                if (StringUtils.isEmpty(excelTPT.getCourseName())) {
                    excelTPT.setFailReason("课程名称未填写");
                    log.warn("导入失败,课程名称未填写,excelFooEntity-{}", excelTPT);
                    return false;
                }
                if (StringUtils.isEmpty(excelTPT.getCapacity())) {
                    excelTPT.setFailReason("上课班容量未填写");
                    log.warn("导入失败,上课班容量未填写,excelFooEntity-{}", excelTPT);
                    return false;
                }
                 if (StringUtils.isEmpty(excelTPT.getSchoolYear())) {
                    excelTPT.setFailReason("学期学年未填写");
                    log.warn("导入失败,学期学年未填写,excelFooEntity-{}", excelTPT);
                    return false;
                }
                //根据课程code查找课程ID
                List<CourseModel> courseModel =courseService.findByCode(excelTPT.getCourseCode());
                String courseId=courseModel.get(0).getId();
                if(courseModel.isEmpty()){
                    excelTPT.setFailReason("课程code" +excelTPT.getCode() +"不存在" );
                    log.warn("课程code" +excelTPT.getCode() +"不存在" );
                    return false;
               }
               String code=excelTPT.getCode();
                //通过上课班code和课程code查询上课班信息
                List<TeachClassModel> teachClassModel = teachClassDao.findTeachClassByCodeAndCourseId(code, courseId);
                //判断是否存在该上课班code，存在记录下错误原因
                if (!CollectionUtils.isEmpty(teachClassModel)) {
                    excelTPT.setFailReason("该上课班code" +excelTPT.getCode() + "已存在对应的课程code" + excelTPT.getCourseCode() );
                    log.warn("该上课班code" +excelTPT.getCode() + "已存在对应的课程code" + excelTPT.getCourseCode());
                    return false;
                }
                if(!courseModel.get(0).getName().equals(excelTPT.getCourseName()) ){
                    excelTPT.setFailReason("课程code" +excelTPT.getCode() + "和对应的课程名称"
                            + excelTPT.getCourseName()+"不匹配" );
                    log.warn("课程code" +excelTPT.getCode() + "和对应的课程名称"
                            + excelTPT.getCourseName()+"不匹配");
                    return false;
                }

                TeachClassEntity teachClassEntity = new TeachClassEntity();
                //将导入内容放到entity中对应的属性中去
                BeanUtils.copyProperties(excelTPT, teachClassEntity);
                //不存在即将专业code存入
                teachClassEntity.setCode(excelTPT.getCode());
                teachClassEntity.setName(excelTPT.getName());
                teachClassEntity.setCourseId(courseId);
                teachClassEntity.setSchoolYear(excelTPT.getSchoolYear());
                teachClassEntity.setCapacity(Integer.parseInt(excelTPT.getCapacity()));
                return true;
            }


    @Override
    public Integer findCodeIsExist(String code){
        return teachClassDao.findByCode(code);
    }


    @Override
    public List<TeachClassModel>  findteachClassByCode(String teachClassCode){
        return teachClassDao.findteachClassByCode(teachClassCode);
    }


    @Override
    public String  findIdIsExist(String courseId, String teachClassCode){
        return teachClassDao.findIdIsExist( courseId,  teachClassCode);
    }


    @Override
    public ItooResult exportAllByIds(HttpServletResponse response, List<String> idList){
        Map<Serializable, Serializable> map = new HashMap<>(16);

        //sheet的名字
        map.put(SHEET_NAME, "上课班信息");
        //需要导入的字段
        map.put(COLUMNS, new String[]{"code","name","courseCode","courseName","schoolYear","capacity"});
        //表格的标题
        map.put(TITLE, "上课班信息");
        map.put(NAME, "上课班信息模板");
        //要导出的数据
        List<TeachClassExportTemplate> teachClassExportTemplateList = new ArrayList<>();
        List<TeachClassModel> teachClassModelList = teachClassService.queryTeachClassInfoByIds(idList);
        for (TeachClassModel teachClassModel : teachClassModelList) {
            List<CourseModel> courseModels= courseService.findByCode(teachClassModel.getCode());
            TeachClassExportTemplate teachClassExportTemplate = new TeachClassExportTemplate();
            BeanUtils.copyProperties(teachClassModel, teachClassExportTemplate);
            teachClassExportTemplate.setCapacity(String.valueOf(teachClassModel.getCapacity()));
            teachClassExportTemplateList.add(teachClassExportTemplate);
        }
        //为空不进行导出
        if (teachClassExportTemplateList.size() == 0) {
            return ItooResult.build(ItooResult.FAIL, "没有要导出的数据！");
        }
        map.put(DATA_LIST, (Serializable) teachClassExportTemplateList);

        //导出
        try {
            ExcelUtil.exportExcel(map, response);
        } catch (Exception e) {
            log.error("导出失败,未知的异常--" + e);
            return ItooResult.build(ItooResult.FAIL, "导出信息失败！",e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导出信息成功！");
    }


    @Override
    public List<TeachClassModel>  queryTeachClassInfoByIds(List<String> idList){
        return teachClassDao.queryTeachClassInfoByIds(idList);
    }

    @Override
    public ItooResult exportByStrLike(HttpServletResponse response, String schoolYear, String code, String name){
        Map<Serializable, Serializable> map = new HashMap<>(16);

        //sheet的名字
        map.put(SHEET_NAME, "上课班信息");
        //需要导入的字段
        map.put(COLUMNS, new String[]{"code","name","courseCode","courseName","schoolYear","capacity"});
        //表格的标题
        map.put(TITLE, "上课班信息");
        map.put(NAME, "上课班信息模板");
        //要导出的数据
        List<TeachClassExportTemplate> teachClassExportTemplateList = new ArrayList<>();

        List<TeachClassModel> teachClassModelList = teachClassService.queryByStrLike( schoolYear, code, name);
        for (TeachClassModel teachClassModel : teachClassModelList) {

            TeachClassExportTemplate teachClassExportTemplate = new TeachClassExportTemplate();
            BeanUtils.copyProperties(teachClassModel, teachClassExportTemplate);
            teachClassExportTemplate.setCapacity(String.valueOf(teachClassModel.getCapacity()));
            teachClassExportTemplateList.add(teachClassExportTemplate);
        }
        //为空不进行导出
        if (teachClassExportTemplateList.size() == 0) {
            return ItooResult.build(ItooResult.FAIL, "没有要导出的数据！");
        }
        map.put(DATA_LIST, (Serializable) teachClassExportTemplateList);

        //导出
        try {
            ExcelUtil.exportExcel(map, response);
        } catch (Exception e) {
            log.error("导出失败,未知的异常--" + e);
            return ItooResult.build(ItooResult.FAIL, "导出信息失败！",e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导出信息成功！");
    }


    @Override
    public boolean downErrorList(String errorListId, HttpServletResponse response){
        // redis 取出没有成功导入的人员信息
        Set set = redisTemplate.opsForZSet().range(errorListId, 0, -1);
        List<TeachClassExportTemplate> teachClassExportTemplate = new ArrayList<>(set);
        // 清空redis数据
        redisTemplate.delete(errorListId);

        //导出
        if (teachClassExportTemplate.size() == 0) {
            return false;
        }
        Map<Serializable, Serializable> errorMap = new HashMap<>(16);


        //sheet的名字
        errorMap.put(SHEET_NAME, "上课班信息");
        //需要导入的字段
        errorMap.put(COLUMNS, new String[]{"code","name","courseCode","courseName","schoolYear","capacity","failReason"});
        //表格的标题
        errorMap.put(TITLE, "上课班信息");
        errorMap.put(NAME, "上课班信息模板");

        errorMap.put(DATA_LIST, (Serializable) teachClassExportTemplate);

        try {
            ExcelUtil.exportExcel(errorMap, response);
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    @Override
    public List<TeachClassModel> queryByStrLike(String schoolYear, String code, String name){
        return teachClassDao.queryByStrLike( schoolYear, code, name);
    }

    @Override
    public Boolean checkbycode(String code) {
        Boolean boolcode=false;
        if(teachClassDao.checkbycode(code)>0){
            boolcode=true;
        }
        return boolcode;
    }

    @Override
    public boolean checkbyname(String name) {
        Boolean boolcode = false;
        if(teachClassDao.checkbyname(name)>0){
            boolcode=true;
        }
        return boolcode;
    }


    @Override
    public TeachClassEntity queryBycode(String code) {
        return teachClassDao.queryBycode(code);
    }


    @Override
    public TeachClassEntity queryByname(String name) {
        return teachClassDao.queryByname(name);
    }


    @Override
    public PageInfo<TeachClassModel> queryAll(Integer pageNo, Integer pageSize){
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<>(teachClassDao.queryAll( ));
    }

    @Override
    public List<TeachClassModel>  findTeachClassByCodeAndCourseId (String code, String courseId){
        return teachClassDao.findTeachClassByCodeAndCourseId( code, courseId);
    }


    /**
     * 面对面建组
     * @param faceToFaceModel 分组学生实体
     * @return ItooResult 组内人员信息
     * @author 郄子硕
     * @since  2019-2-24 15:44:27
     */
    @Override
    public ItooResult faceToFaceAddClass(FaceToFaceModel faceToFaceModel) {
        // 存入缓存redis
        String classKey = "FaceToFaceNum" + faceToFaceModel.getKeyText();
        String classMembersKey = "FaceToFaceMember" + faceToFaceModel.getKeyText();

        //一、为null时候表示第一个人进来了，这时候需要存入缓存
        if (redisTemplate.opsForValue().get(classKey) == null) {
            // 设置结组状态 为未开始
            faceToFaceModel.setFlag(false);
            // 存入群组信息
            redisTemplate.opsForValue().set(classKey, faceToFaceModel);
            redisTemplate.expire(classKey, 120, TimeUnit.SECONDS);
            // 存入成员信息
            redisTemplate.opsForSet().add(classMembersKey, faceToFaceModel.getStudentClassInfoModel());
            redisTemplate.expire(classMembersKey, 120, TimeUnit.SECONDS);

            FaceToFaceModel groupFaceToFaceModel = (FaceToFaceModel) redisTemplate.opsForValue().get(classKey);
            Set members = redisTemplate.opsForSet().members(classMembersKey);
            groupFaceToFaceModel.setStudentClassSet(members);
            return ItooResult.build("0000", "第一个人已经进群了！", groupFaceToFaceModel);
        }


        // 二 . 已经不是第一个人进群了，从第二个人进入开始正在面对面建群
        FaceToFaceModel groupFaceToFaceModel = (FaceToFaceModel) redisTemplate.opsForValue().get(classKey);

        if (groupFaceToFaceModel.isFlag()) {
            Set members = redisTemplate.opsForSet().members(classMembersKey);
            // 把所有的成员放入面对面实体中
            groupFaceToFaceModel.setStudentClassSet(members);
            return ItooResult.build("0001", "面对面建群已经结束！", groupFaceToFaceModel);

        } else {

            if (!("".equals(groupFaceToFaceModel.getTeacherName()))) {
                // 老师已经进群了，设定面对面实体中老师的姓名和id-- 更新分组内的教师信息
                faceToFaceModel.setTeacherName(groupFaceToFaceModel.getTeacherName());
                faceToFaceModel.setTeacherId(groupFaceToFaceModel.getTeacherId());
            }
            // 更新分组信息
            redisTemplate.opsForValue().set(classKey, faceToFaceModel);
            // 更新成员信息
            redisTemplate.opsForSet().add(classMembersKey, faceToFaceModel.getStudentClassInfoModel());

            FaceToFaceModel groupFaceToFaceModelCurrent = (FaceToFaceModel) redisTemplate.opsForValue().get(classKey);
            Set membersCurrent = redisTemplate.opsForSet().members(classMembersKey);
            groupFaceToFaceModelCurrent.setStudentClassSet(membersCurrent);
            return ItooResult.build("0000", "陆续进群中！", groupFaceToFaceModelCurrent);

        }

    }

    /**
     * 确认分组后，获取组id
     *
     * @return ItooResult
     * @author 郄子硕
     * @since 2019-2-24 15:44:27
     */
    @Override
    public ItooResult insertClassInfo() {
        TeachClassEntity teachClassEntity = new TeachClassEntity();
        teachClassEntity.setId(IdWorker.getIdStr());
        teachClassEntity.setCode(teachClassService.addClassByCode());
        teachClassEntity.setSchoolYear(YearSemester.getYearSemesterCode(0,0).get(0));
        teachClassEntity.setName("");
        boolean save = teachClassService.save(teachClassEntity);
        if (save) {
            // 添加分组信息成功--返回组id
            return ItooResult.build(ItooResult.SUCCESS, "添加分组成功", teachClassEntity);
        } else {
            // 添加分组信息失败
            log.error("面对面建群--添加分组获取组id失败");
            return ItooResult.build(ItooResult.FAIL, "添加分组获取组id失败");
        }
    }


    /**
     * 填写分组信息，更新分组信息
     *
     * @return ItooResult
     * @author 郄子硕
     * @since 2019-2-24 15:44:27
     */
    @Override
    public ItooResult updateClassInfo(TeachClassEntity teachClassEntity) {
        if ("".equals(teachClassEntity.getId())) {
            log.error("面对面建群--根据id更新分组信息失败，分组id为空-{}", teachClassEntity);
            return ItooResult.build(ItooResult.FAIL, "分组id不能为空");
        }
        boolean update = teachClassService.updateById(teachClassEntity);
        if (update) {
            // 添加分组信息成功--返回组id
            return ItooResult.build(ItooResult.SUCCESS, "更新分组信息成功", teachClassEntity);
        } else {
            // 添加分组信息失败
            log.error("面对面建群--根据id更新分组信息失败,分组信息--{}", teachClassEntity);
            return ItooResult.build(ItooResult.FAIL, "根据id更新分组信息失败");
        }
    }


    /**
     * 确认建组，将组内所有人员添加到库里
     * *
     *
     * @param faceToFaceModel
     * @return ItooResult
     * @author 郄子硕
     * @since 2019-2-24 15:44:27
     */
    @Override
    public ItooResult confirmCreateClass(FaceToFaceModel faceToFaceModel) {
        String groupKey = "FaceToFaceNum" + faceToFaceModel.getKeyText();
        // 保存教师信息
        TeacherTeachClassEntity teacherTeachClassEntity = new TeacherTeachClassEntity();
        teacherTeachClassEntity.setTeacherId(faceToFaceModel.getTeacherId());
        teacherTeachClassEntity.setTeachClassId(faceToFaceModel.getClassId());
        teacherTeachClassEntity.setSchoolYear(YearSemester.getYearSemesterCode(0,0).get(0));
        boolean saveTeacherInfo = teacherTeachClassService.save(teacherTeachClassEntity);
        if (saveTeacherInfo) {
            // 批量保存学生信息
            if (faceToFaceModel.getStudentClassSet().size() == 0) {
                return ItooResult.build(ItooResult.SUCCESS, "保存学生分组与教师信息成功！");
            }else {
                List<StudentTeachClassEntity> studentList = new ArrayList<>();
                StudentTeachClassEntity studentInfoEntity = new StudentTeachClassEntity();
//                for (int i=0;i<faceToFaceModel.getStudentClassSet().size();i++){
                 //   studentList.get(i).setStudentId() =
//                    Iterator<StudentTeachClassModel> iterator = faceToFaceModel.getStudentClassSet().iterator();
//                    while (iterator.hasNext()) {
//
//                    }
//                }
//                Iterator iter = faceToFaceModel.getStudentClassSet().iterator();
//                while(iter.hasNext()){
//                    String str = (String) iter.next();
//                    System.out.println(str);
//                }
                //Set转List
                List<StudentTeachClassModel> result =new ArrayList(faceToFaceModel.getStudentClassSet());


                for (int i=0;i<result.size();i++){
//                    String studentId = result.get(i).getStudentId();
//                    studentInfoEntity.setStudentId(studentId);
//                    String teachClassId = result.get(i).getTeachClassId();
//                    studentInfoEntity.setTeachClassId(teachClassId);
                    BeanUtils.copyProperties(result.get(i),studentInfoEntity);

                    studentList.add(studentInfoEntity);
                }

                boolean saveBatchStudent = studentTeachClassService.saveBatch(studentList);
                if (saveBatchStudent) {
                    FaceToFaceModel groupFaceToFaceModel = (FaceToFaceModel) redisTemplate.opsForValue().get(groupKey);
                    groupFaceToFaceModel.setFlag(true);
                    redisTemplate.opsForValue().set(groupKey, groupFaceToFaceModel);

                    redisTemplate.expire(groupKey, 60, TimeUnit.SECONDS);

                    return ItooResult.build(ItooResult.SUCCESS, "保存学生分组与教师信息成功！");
                } else {
                    log.error("面对面建群--保存学生分组与教师信息失败", faceToFaceModel);
                    return ItooResult.build(ItooResult.FAIL, "保存学生分组与教师信息失败！");
                }
            }
        } else{
            log.error("面对面建群--保存学生分组与教师信息失败", faceToFaceModel);
            return ItooResult.build(ItooResult.FAIL, "保存学生分组与教师信息失败！");
        }
    }


    @Override
    public String addClassByCode(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        return result;
    }


}
